package group.igfd.manager.biz.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import group.igfd.manager.biz.entity.*;
import group.igfd.manager.biz.model.GoodDetail;
import group.igfd.manager.biz.model.GoodLabel;
import group.igfd.manager.biz.model.PublisherCustomersModel;
import group.igfd.manager.biz.service.*;
import io.renren.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import group.igfd.manager.biz.dao.PublishCustomersDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;


@Service("publishCustomersService")
public class PublishCustomersServiceImpl extends ServiceImpl<PublishCustomersDao, PublishCustomersEntity> implements PublishCustomersService {

    @Autowired
    private BrandsService brandsService;
    @Autowired
    private CategoriesService categoriesService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private QuotesService quotesService;
    @Autowired
    private PicturesService picturesService;
    @Autowired
    private PublishExpertsService publishExpertsService;
    @Autowired
    private LabelExpertService labelExpertService;
    @Autowired
    private PublishBuyersService publishBuyersService;
    @Autowired
    private ISmsService smsService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        EntityWrapper<PublishCustomersEntity> ew = new EntityWrapper<>();

        if(!ObjectUtils.isEmpty(params.get("uid"))){
            ew.eq("uid", params.get("uid"));
        }
        if(!ObjectUtils.isEmpty(params.get("categoryId"))){
            CategoriesEntity categoriesEntity = categoriesService.selectById(params.get("categoryId") + "");
            if (categoriesEntity != null) {
                if (categoriesEntity.getFatherId() != 0) {
                    ew.eq("type", categoriesEntity.getId());
                } else {
                    List<String> categoryList = new ArrayList<>();

                    EntityWrapper<CategoriesEntity> categoriesEntityEntityWrapper = new EntityWrapper<>();
                    categoriesEntityEntityWrapper.eq("father_id",categoriesEntity.getId());
                    List<CategoriesEntity> categoriesEntities = categoriesService.selectList(categoriesEntityEntityWrapper);
                    for (CategoriesEntity categoriesEntity1:categoriesEntities) {
                        categoryList.add(String.valueOf(categoriesEntity1.getId()));
                    }

                    ew.in("type",categoryList);
                }
            }

        }
        if(!ObjectUtils.isEmpty(params.get("title"))){
            ew.like(true, "title", params.get("title")+"");
        }
        if(!ObjectUtils.isEmpty(params.get("minDt"))){
            String minDt = params.get("minDt")+"";
            ew.ge("created_at", minDt +" 00:00:00");
        }

        if(!ObjectUtils.isEmpty(params.get("maxDt"))){
            String minDt = params.get("maxDt")+"";
            ew.le("created_at", minDt +" 23:59:59");
        }

        if(!ObjectUtils.isEmpty(params.get("brandId"))){
            ew.eq("brand", params.get("brandId"));
        }

        if(!ObjectUtils.isEmpty(params.get("fullName"))){
            ew.like(true, "full_name", params.get("fullName") + "");
        }
        if(!ObjectUtils.isEmpty(params.get("flag"))){
            ew.eq("flag", params.get("flag"));
        }
        ew.orderBy("created_at",false);
        Page<PublishCustomersEntity> page = this.selectPage(
                new Query<PublishCustomersEntity>(params).getPage(),
                ew
        );

        Page<PublisherCustomersModel> newPage = new Page<>();

        newPage.setTotal(page.getTotal());
        newPage.setCurrent(page.getCurrent());
        newPage.setSize(page.getSize());
        List<PublisherCustomersModel> list = new ArrayList<>();

        if( page.getRecords() != null && page.getRecords().size() > 0){
            for(PublishCustomersEntity entity : page.getRecords()){
                PublisherCustomersModel model = new PublisherCustomersModel();
                model.setId(entity.getId());
                model.setNickName(usersService.getNickName(entity.getUid()));
                model.setTitle(entity.getTitle());
//                model.setTitlePic(entity.getTitlePicture());
                model.setBrand(brandsService.getBrandName(entity.getBrand()));
                model.setType(categoriesService.getCategoryName(entity.getType()));
                model.setSku(entity.getSku());
                model.setColor(entity.getColor());
                model.setSize(entity.getSize());
                model.setSex(entity.getSex());
                model.setFullName(entity.getFullName());
                model.setFlag(entity.getFlag());

                QuotesEntity quotes_entity = quotesService.getQuotesInfo(entity.getId());

                if (quotes_entity == null) {
                    model.setQuotesPrice("");
                    model.setQuotesDays("");
                    model.setQuotesStatus(0);
                } else {
                    model.setQuotesPrice(quotes_entity.getPrice());
                    model.setQuotesDays(quotes_entity.getDays());
                    model.setQuotesStatus(quotes_entity.getStatus());
                }

                if (entity.getDeletedAt() != null) {
                    model.setDeletedFlag(1);
                } else {
                    model.setDeletedFlag(0);
                }

                if(null != entity.getCreatedAt())
                    model.setPublishTime(DateUtils.format(entity.getCreatedAt(), DateUtils.DATE_TIME_PATTERN));

                list.add(model);
            }
        }
        newPage.setRecords(list);
        return new PageUtils(newPage);
    }

    @Transactional
    @Override
    public boolean toCustomerGoodsQuotes(PublishCustomersEntity publishCustomers, QuotesEntity quotes) {
        boolean result = false;

        //1.更新客人商品信息
        this.updateAllColumnById(publishCustomers);

        //2.添加报价信息
        quotesService.insert(quotes);

        //3.判断当前需求是否需要自动创建订单
        Integer labelId = publishCustomers.getLabelId();
        if (labelId != null) {

            PublishBuyersEntity publishBuyersEntity = new PublishBuyersEntity();

            publishBuyersEntity.setUid(quotes.getUid());
            publishBuyersEntity.setDay(Integer.valueOf(quotes.getDays()));
            publishBuyersEntity.setBrand(publishCustomers.getBrand());
            publishBuyersEntity.setType(publishCustomers.getType());
            publishBuyersEntity.setColor(publishCustomers.getColor());
            publishBuyersEntity.setDescription(publishCustomers.getDescription());
            publishBuyersEntity.setDiscount(quotes.getRebate().doubleValue());
            publishBuyersEntity.setEurPrice(Double.valueOf(quotes.getPrice()));
            publishBuyersEntity.setSex(publishCustomers.getSex());
            publishBuyersEntity.setSize(publishCustomers.getSize());
            publishBuyersEntity.setSku(publishCustomers.getSku());

            EntityWrapper<PicturesEntity> picturesEntityEntityWrapper = new EntityWrapper<>();
            picturesEntityEntityWrapper.eq("parent_id",publishCustomers.getId());
            picturesEntityEntityWrapper.eq("type", "customer_post");
            PicturesEntity picturesEntity = picturesService.selectOne(picturesEntityEntityWrapper);
            String titlePic = "";
            if (picturesEntity != null) {
                if ("image".equals(picturesEntity.getFileType())) {
                    titlePic = picturesEntity.getUrl();
                } else {
                    titlePic = picturesEntity.getFirstImage();
                }
            }
            publishBuyersEntity.setTitlePicture(titlePic);
            publishBuyersEntity.setDescJson("["+ getDescJson(labelId, titlePic)+"]");

            String brandName = "";
            if (org.apache.commons.lang.StringUtils.isNumeric(publishCustomers.getBrand())) {
                brandName = brandsService.selectById(Integer.valueOf(publishCustomers.getBrand())).getName();
            }

            String categoryName = "";
            if (org.apache.commons.lang.StringUtils.isNumeric(publishCustomers.getType())) {
                categoryName = categoriesService.selectById(Integer.valueOf(publishCustomers.getType())).getName();
            }
            String title = brandName + " " + categoryName;
            publishBuyersEntity.setTitle(title);
            publishBuyersEntity.setCreatedAt(new Date());
            publishBuyersEntity.setUpdatedAt(new Date());

            publishBuyersService.insert(publishBuyersEntity);

            //关联相关的笔记,更新笔记
            EntityWrapper<LabelExpertEntity> labelExpertEntityWrapper = new EntityWrapper<>(new LabelExpertEntity());
            labelExpertEntityWrapper.eq("id",labelId);
            LabelExpertEntity labelExpert = labelExpertService.selectOne(labelExpertEntityWrapper);

            EntityWrapper<PublishExpertsEntity> publishExpertsEntityWrapper = new EntityWrapper<>(new PublishExpertsEntity());
            publishExpertsEntityWrapper.eq("id",labelExpert.getExpertId());
            PublishExpertsEntity publishExperts = publishExpertsService.selectOne(publishExpertsEntityWrapper);
            List<GoodDetail> goodDetailsExpert = JSON.parseObject(publishExperts.getDescJson(), new TypeReference<List<GoodDetail>>() {
            });

            for (GoodDetail goodDetailExpert: goodDetailsExpert) {
                if (goodDetailExpert.getLabels() != null) {
                    for (GoodLabel goodLabel: goodDetailExpert.getLabels()) {
                        if (goodLabel.getLabelId() == labelId) {
                            goodLabel.setBuyerId(String.valueOf(publishBuyersEntity.getId()));
                            break;
                        }
                    }
                }
            }

            publishExperts.setDescJson(JSON.toJSONString(goodDetailsExpert));
            publishExpertsService.updateById(publishExperts);
        }

        //添加短信相关的提醒
        EntityWrapper<UsersEntity> usersEntityEntityWrapper = new EntityWrapper<>();
        usersEntityEntityWrapper.eq("uid",publishCustomers.getUid());
        UsersEntity usersEntity = usersService.selectOne(usersEntityEntityWrapper);
        if (usersEntity != null) {
            Map<String, String> smsJson = new HashMap<>();
            smsJson.put("name",usersEntity.getNickname());
            smsJson.put("title",publishCustomers.getTitle());
            smsJson.put("money","€" + Math.round(Double.valueOf(quotes.getPrice()) * quotes.getRebate().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()));
            smsService.smsNotice("70", usersEntity.getUsername(),smsJson);
        }

        result = true;

        return result;
    }

    private String getDescJson(Integer labelId, String titlePic){
        LabelExpertEntity labelExpert = labelExpertService.selectById(labelId);
        if(null != labelExpert){
            try{
                Integer expertId = labelExpert.getExpertId();
                PublishExpertsEntity publishExperts = publishExpertsService.selectById(expertId);
                if(null != publishExperts){
                    String descJson = publishExperts.getDescJson();
                    if(!StringUtils.isEmpty(descJson)){
                        JSONArray jsonArray = JSON.parseArray(descJson);
                        for (int i = 0; i < jsonArray.size(); i++) {
                            JSONObject jo = jsonArray.getJSONObject(i);
                            if(jo.getString("imageURL").equals(titlePic)){
                                jo.remove("labels");
                                return jo.toJSONString();
                            }
                        }
                    }
                }

            }catch(Exception e){
                //logger.error("根据labelid得到jsonDes异常", e);
            }
        }
        return "";
    }

}
